package com.xnew.dict.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.xnew.bean.common.AcctOrganizationInfo;
import com.xnew.bean.common.DictionaryInfo;
import com.xnew.bean.common.SysUserInfo;
import com.xnew.constant.Constant;
import com.xnew.dict.bean.EvaluateInfo;
import com.xnew.dict.mapper.DictCommonMapper;
import com.xnew.dict.service.DictCommonService;
import com.xnew.org.mapper.OrgMapper;
import com.xnew.user.mapper.AuUserMapper;
import com.xnew.user.service.AuUserService;
import com.xnew.utils.DataInput;
import com.xnew.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 数据字典处理公共使用的service信息
 * @Author yangcd
 * @Date 2020/12/31
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DictCommonServiceImpl implements DictCommonService {
    @Autowired
    private DictCommonMapper dictCommonMapper;

    @Autowired
    private OrgMapper orgMapper;

    @Autowired
    private AuUserService auUserService;
    @Autowired
    private AuUserMapper auUserMapper;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public List<DictionaryInfo> queryDictCommonResult(String type) throws Exception {
        String redisTypeResult = RedisUtil.get(RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.DICT_TYPE, type}));
        return JSONObject.parseObject(redisTypeResult, List.class);
    }

    @Override
    public Map<String, List<DictionaryInfo>> queryDictCommonBatchResult(String types) throws Exception {
        if(null != types && !"".equals(types)){
            Map<String, List<DictionaryInfo>> map = new HashMap<String, List<DictionaryInfo>>();
            String[] dictType = types.split(",");
            for(String type : dictType){
                map.put(type, this.queryDictCommonResult(type));
            }
            return map;
        }
        return null;
    }

    @Override
    public void initDictToRedisResult() throws Exception {
        List<DictionaryInfo> list = dictCommonMapper.initDictToRedisResult();
        Map<String, List<DictionaryInfo>> map = new HashMap<String, List<DictionaryInfo>>();
        String redisKey = null;
        for(DictionaryInfo dictionaryInfo : list){
            redisKey = RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.DICT_TYPE, dictionaryInfo.getType().trim()});
            if(null == map.get(redisKey)){
                List<DictionaryInfo> dictionaryInfoList = new ArrayList<DictionaryInfo>();
                dictionaryInfoList.add(dictionaryInfo);
                map.put(redisKey, dictionaryInfoList);
            }else{
                List<DictionaryInfo> dictionaryInfoList = map.get(redisKey);
                dictionaryInfoList.add(dictionaryInfo);
                map.put(redisKey, dictionaryInfoList);
            }
        }

        //适用于地区编码
        List<DictionaryInfo> dictionaryInfolist = this.queryDictCommonRegion();
        for(DictionaryInfo dictionaryInfo : dictionaryInfolist){
            redisKey = RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.DICT_TYPE, Constant.REGION});
            if(null == map.get(redisKey)){
                List<DictionaryInfo> dictionaryInfoList = new ArrayList<DictionaryInfo>();
                dictionaryInfoList.add(dictionaryInfo);
                map.put(redisKey, dictionaryInfoList);
            }else{
                List<DictionaryInfo> dictionaryInfoList = map.get(redisKey);
                dictionaryInfoList.add(dictionaryInfo);
                map.put(redisKey, dictionaryInfoList);
            }
        }

        //适用于地区编码二级（省、市）
        List<DictionaryInfo> dictionaryInfoAbslist = this.queryDictCommonRegionTwoLe();
        for(DictionaryInfo dictionaryInfo : dictionaryInfoAbslist){
            redisKey = RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.DICT_TYPE, Constant.REGION_TWO_LE});
            if(null == map.get(redisKey)){
                List<DictionaryInfo> dictionaryInfoList = new ArrayList<DictionaryInfo>();
                dictionaryInfoList.add(dictionaryInfo);
                map.put(redisKey, dictionaryInfoList);
            }else{
                List<DictionaryInfo> dictionaryInfoList = map.get(redisKey);
                dictionaryInfoList.add(dictionaryInfo);
                map.put(redisKey, dictionaryInfoList);
            }
        }

        //适用于处罚名称联动
        List<DictionaryInfo> dictionaryPublishInfolist = this.queryDictCommonAttriType("DG0012");
        for(DictionaryInfo dictionaryInfo : dictionaryPublishInfolist){
            redisKey = RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.DICT_TYPE, Constant.PUBLISH});
            if(null == map.get(redisKey)){
                List<DictionaryInfo> dictionaryInfoList = new ArrayList<DictionaryInfo>();
                dictionaryInfoList.add(dictionaryInfo);
                map.put(redisKey, dictionaryInfoList);
            }else{
                List<DictionaryInfo> dictionaryInfoList = map.get(redisKey);
                dictionaryInfoList.add(dictionaryInfo);
                map.put(redisKey, dictionaryInfoList);
            }
        }

        //会员属性机构类型
        List<DictionaryInfo> dictMemberInfolist = this.queryDictCommonAttriType("MEMBER_TYPE");
        for(DictionaryInfo dictionaryInfo : dictMemberInfolist){
            redisKey = RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.DICT_TYPE, Constant.ATTRIBUTE_TYPE});
            if(null == map.get(redisKey)){
                List<DictionaryInfo> dictionaryInfoList = new ArrayList<DictionaryInfo>();
                dictionaryInfoList.add(dictionaryInfo);
                map.put(redisKey, dictionaryInfoList);
            }else{
                List<DictionaryInfo> dictionaryInfoList = map.get(redisKey);
                dictionaryInfoList.add(dictionaryInfo);
                map.put(redisKey, dictionaryInfoList);
            }
        }

        //适用于纠纷性质
        List<DictionaryInfo> dictInfolist = this.queryDictCommonLinkage("DG0129");
        for(DictionaryInfo dictionaryInfo : dictInfolist){
            redisKey = RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.DICT_TYPE, Constant.DISPUTE});
            if(null == map.get(redisKey)){
                List<DictionaryInfo> dictionaryInfoList = new ArrayList<DictionaryInfo>();
                dictionaryInfoList.add(dictionaryInfo);
                map.put(redisKey, dictionaryInfoList);
            }else{
                List<DictionaryInfo> dictionaryInfoList = map.get(redisKey);
                dictionaryInfoList.add(dictionaryInfo);
                map.put(redisKey, dictionaryInfoList);
            }
        }

        this.buildDictRedisResult(map);
        logger.info("执行结束");
    }

    /**
     * 根据评价类型查询评价内容
     * @Param evaluateType 评价类型
     * @return List<EvaluateInfo> 评价信息结果集
     * */
    @Override
    public List<EvaluateInfo> buildEvaluateList(String evaluateType) throws Exception{
        return dictCommonMapper.buildEvaluateList(evaluateType);
    }

    public void buildDictRedisResult(Map<String, List<DictionaryInfo>> map){
        Set<String> set = map.keySet();
        Iterator<String> iterator = set.iterator();
        String key = null;
        while (iterator.hasNext()){
            key = iterator.next();
            RedisUtil.del(key);
            RedisUtil.set(key, JSONObject.toJSONString(map.get(key)));
        }
    }

    @Override
    public void initOrgAndUserResult() throws Exception {
        List<SysUserInfo> list = auUserService.queryAllUserNameList();
        for(SysUserInfo userInfo : list){
            RedisUtil.set(RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.USER_ORG_TYPE, Constant.USER_NAME, userInfo.getUserInfoNo()}), userInfo.getUserName());
//            RedisUtil.set(RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.USER_ORG_TYPE, Constant.USER_ORG_ID, userInfo.getUserId()}), userInfo.getOrgId());
//            RedisUtil.set(RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.USER_ORG_TYPE, Constant.USER_ORG_ALL_ID, userInfo.getUserId()}), userInfo.getOrgIdStr());
//            RedisUtil.set(RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.USER_ORG_TYPE, Constant.USER_ORG_NAME, userInfo.getUserId()}), userInfo.getOrgName());
//            RedisUtil.set(RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.USER_ORG_TYPE, Constant.USER_ORG_ALL_NAME, userInfo.getUserId()}), userInfo.getOrgNameStr());
        }
        List<AcctOrganizationInfo> orgList = orgMapper.queryAllOrgList();
        for(AcctOrganizationInfo acctOrganizationInfo : orgList){
            RedisUtil.set(RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.USER_ORG_TYPE, Constant.ORG_NAME, acctOrganizationInfo.getOrgId()}), acctOrganizationInfo.getOrgName());
            RedisUtil.set(RedisUtil.buildKey(":", new String[]{Constant.SYSTEM_NAME, Constant.USER_ORG_TYPE, Constant.ORG_ALL_NAME, acctOrganizationInfo.getOrgId()}), acctOrganizationInfo.getOrgAllName());
        }
    }

    private List<AcctOrganizationInfo> allList = new ArrayList<AcctOrganizationInfo>();
    @Override
    public void buildOrgAllName() throws Exception {
        List<AcctOrganizationInfo> list = orgMapper.queryChildOrgListById("0");
        this.setOrgAllName(list, "", "");
    }

    @Override
    public void initUserPassword() {
        List<SysUserInfo> list = auUserMapper.selectAll(new HashMap());
        for(SysUserInfo user : list){
            auUserService.resetPassword(user.getUserInfoNo(), user.getLoginName());
        }
    }

    @Override
    public void saveDictTypeCommon(String typeCode, String typeName) throws Exception {
        dictCommonMapper.saveDictTypeCommon(typeCode, typeName);
        this.initDictToRedisResult();
    }

    @Override
    public void saveDictCodeCommon(Map<String, Object> map) throws Exception {
        dictCommonMapper.saveDictCodeCommon(map);
        this.initDictToRedisResult();
    }

    @Override
    public List<Map<String, Object>> queryDictType(String typeCode) throws Exception {
        return dictCommonMapper.queryDictType(typeCode);
    }

    @Override
    public List<Map<String, Object>> queryDictTypeList(DataInput input) throws Exception {
        PageHelper.startPage(input.getPageNum(), input.getPageSize());
        return dictCommonMapper.queryDictTypeList(input.getParam());
    }

    @Override
    public List<Map<String, Object>> queryDictCodeBean(String type, String code) throws Exception {
        return dictCommonMapper.queryDictCodeBean(type, code);
    }

    @Override
    public List<DictionaryInfo> queryDictCommonRegion() throws Exception {
        //地区三级编码联动
        List<DictionaryInfo> dictionaryList = dictCommonMapper.queryDictCommonRegion();
        return queryDictList(dictionaryList);
    }

    public List<DictionaryInfo> queryDictCommonRegionTwoLe() throws Exception {
        //地区二级编码联动
        List<DictionaryInfo> dictionaryList = dictCommonMapper.queryDictCommonRegionTwoLe();
        return queryDictList(dictionaryList);
    }


    /**
     * 联动查询递归方法ParentId
     * @param dictList
     * @return
     * @throws Exception
     */
    public List<DictionaryInfo> queryDictList(List<DictionaryInfo> dictList) throws Exception {
    // 最后的结果
    List<DictionaryInfo> dictAllList = new ArrayList<DictionaryInfo>();
    // 先找到所有的一级
        for (int i = 0; i < dictList.size(); i++) {
            dictList.get(i).setStatus(false);
        // 一级菜单parentId  type
        if (Constant.PROVINCE_LEV01.equals(dictList.get(i).getParentId())){
            dictList.get(i).setStatus(true);
            dictAllList.add(dictList.get(i));
        }
    }
    // 为一级设置子层级，getChild是递归调用的
        for (DictionaryInfo dict : dictAllList) {
        //menu.setSysMenuVoChild(this.getChild(menu.getId(), menuList));
        dict.setChildren(this.getChilId(dict.getId(), dictList)); //获取ID
    }
        return dictAllList;
}

    @Override
    public List<DictionaryInfo> queryDictCommonPublish() throws Exception {
        List<DictionaryInfo> dictionaryList = dictCommonMapper.queryDictCommonLinkage(Constant.PUBLISH);
        // 最后的结果
        List<DictionaryInfo> dictAllList = new ArrayList<DictionaryInfo>();
        // 先找到所有的一级
        for (int i = 0; i < dictionaryList.size(); i++) {
            dictionaryList.get(i).setStatus(false);
            // 一级菜单parentId  type
            if (Constant.DG0012_LEV01.equals(dictionaryList.get(i).getParentId())){
                dictionaryList.get(i).setStatus(true);
                dictAllList.add(dictionaryList.get(i));
            }
        }
        // 为一级设置子层级，getChild是递归调用的
        for (DictionaryInfo dict : dictAllList) {
            //menu.setSysMenuVoChild(this.getChild(menu.getId(), menuList));
            dict.setChildren(this.getChilId(dict.getId(), dictionaryList)); //获取ID
        }
        return dictAllList;
    }

    @Override
    public List<DictionaryInfo> queryDictCommonLinkage(String type) throws Exception {
        List<DictionaryInfo> dictionaryList = dictCommonMapper.queryDictCommonLinkage(type);


        // 最后的结果
        List<DictionaryInfo> dictAllList = new ArrayList<DictionaryInfo>();
        // 先找到所有的一级
        for (int i = 0; i < dictionaryList.size(); i++) {
            dictionaryList.get(i).setStatus(false);
            // 一级菜单parentId  type
            if (type.equals(dictionaryList.get(i).getParentId())){
                dictionaryList.get(i).setStatus(true);
                dictAllList.add(dictionaryList.get(i));
            }
        }
        // 为一级设置子层级，getChild是递归调用的
        for (DictionaryInfo dict : dictAllList) {
            //menu.setSysMenuVoChild(this.getChild(menu.getId(), menuList));
            dict.setChildren(this.getChildCode(dict.getCode(), dictionaryList));
        }
        return dictAllList;
    }

    /**
     * 拼接会员属性机构类型树
     * @param type
     * @return
     * @throws Exception
     */
    @Override
    public List<DictionaryInfo> queryDictCommonAttriType(String type) throws Exception {
        List<DictionaryInfo> dictionaryList = dictCommonMapper.queryDictCommonLinkage(type);
        // 最后的结果
        List<DictionaryInfo> dictAllList = new ArrayList<DictionaryInfo>();
        // 先找到所有的一级
        for (int i = 0; i < dictionaryList.size(); i++) {
            dictionaryList.get(i).setStatus(false);
            // parentId  type
            if (type.equals(dictionaryList.get(i).getParentId())
                    && !"F".equals(dictionaryList.get(i).getCode())
                    && !"G".equals(dictionaryList.get(i).getCode())
                    && !"H".equals(dictionaryList.get(i).getCode())
                    && !"I".equals(dictionaryList.get(i).getCode())
                    && !"J".equals(dictionaryList.get(i).getCode())
            ){
                dictionaryList.get(i).setStatus(true);
                dictAllList.add(dictionaryList.get(i));
            }
        }
        // 为一级设置子层级，getChild是递归调用的
        for (DictionaryInfo dict : dictAllList) {
            dict.setChildren(this.getChilId(dict.getId(), dictionaryList));
        }
        return dictAllList;
    }

    /**
     * 递归查找子菜单及资源 ID
     * @return
     */
    private List<DictionaryInfo> getChilId(String str, List<DictionaryInfo> rootDict) {
        List<DictionaryInfo> childList = new ArrayList<>();
        for (DictionaryInfo dict : rootDict) {
//			if (!menu.getStatus()) {
            if (dict.getParentId().equals(str)) {
//					menu.setStatus(true);
                childList.add(dict);
            }
//			}
        }
        for (DictionaryInfo dict : childList) {
            List<DictionaryInfo> child = getChilId(dict.getId(), rootDict);
            //menu.setSysMenuVoChild(child);
            dict.setChildren(child);
        }
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

    /**
     * 递归查找子级及资源 code
     * @return
     */
    private List<DictionaryInfo> getChildCode(String str, List<DictionaryInfo> rootDict) {
        List<DictionaryInfo> childList = new ArrayList<>();
        for (DictionaryInfo dict : rootDict) {
//			if (!menu.getStatus()) {
            if (dict.getParentId().equals(str)) {
//					menu.setStatus(true);
                childList.add(dict);
            }
//			}
        }
        for (DictionaryInfo dict : childList) {
            List<DictionaryInfo> child = getChildCode(dict.getCode(), rootDict);
            //menu.setSysMenuVoChild(child);
            dict.setChildren(child);
        }
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

    public void setOrgAllName(List<AcctOrganizationInfo> list, String parentOrgId, String parentOrgName) throws Exception{
        for(AcctOrganizationInfo acctOrganizationInfo: list){
            acctOrganizationInfo.setOrgAllName(parentOrgName + acctOrganizationInfo.getOrgName()+"/");
            acctOrganizationInfo.setOrgAllId(parentOrgId + acctOrganizationInfo.getOrgId()+"/");
            allList.add(acctOrganizationInfo);
            List<AcctOrganizationInfo> queryOrgList = orgMapper.queryChildOrgListById(acctOrganizationInfo.getOrgId());
            orgMapper.updateOrgAllName(acctOrganizationInfo);
            this.setOrgAllName(queryOrgList, acctOrganizationInfo.getOrgAllId(), acctOrganizationInfo.getOrgAllName());
        }
    }
}
